<template>
	<view class="wrap">
		<v-top-header />
		<v-menu />
		<view v-if="vuex_user.videoPer === '1'">
			<view class="category-items">
				<view v-for="(item,index) in videoList" :key="index" @click="doStartVideo(item.ID)"
					:class="['category-item',item.ID === currentVideoId?'category-item-active':'']">
					{{item.des}}
				</view>
			</view>
			<video id="video" style="width:100%" :src="stream_url" autoplay v-if="stream_url" :play-strategy="3" />
			<u-empty text="请选择视频" v-else></u-empty>
		</view>
		<u-empty mode="permission" v-else></u-empty>
	</view>
</template>

<script>
	let heart_beat_inteval = null
	import vTopHeader from '@/components/v-top-header.vue'
	import vMenu from '@/components/v-menu.vue'
	export default {
		components: {
			vTopHeader,
			vMenu
		},
		data() {
			return {
				videoContext: null,
				videoList: [],
				currentVideoId: null
			}
		},
		computed: {
			stream_url() {
				if (this.vuex_ip_current.ip && this.currentVideoId) {
					return 'rtmp://' + this.vuex_ip_current.ip + '/live/stream_' + this.currentVideoId
				}
				return null
			}
		},
		watch: {
			vuex_device(newVal, oldVal) {
				this.doStopVideo()
				this.loadVideoList()
			}
		},
		onUnload() {
			this.doStopVideo()
		},
		onHide() {
			this.doStopVideo()
		},
		methods: {
			loadVideoList() {
				if (this.vuex_device && this.vuex_device.value) {
					this.$u.api.getVideoList({
						deviceId: this.vuex_device.value
					}).then(res => {
						if (res.result === 1) {
							this.videoList = res.data
						}
					})
				}
			},
			doStartVideo(videoId) {
				//stop current video ,if exist
				this.doStopVideo()
				let that = this
				this.$u.api.startVideo({
					videoId: videoId
				}).then(res => {
					if (res.result === 1) {
						this.currentVideoId = videoId
						heart_beat_inteval = setInterval(() => {
							that.doVideoHeartBeat()
						}, 1000)
					} else {
						this.$u.toast(res.data.reason)
					}
					console.log(this.stream_url)
				})
			},
			doVideoHeartBeat() {
				console.log(this.stream_url)
				console.log('send video heart beat=====>')
				this.$u.api.sendVideoHeartBeat({
					videoId: this.currentVideoId
				})
			},
			doStopVideo() {
				if (heart_beat_inteval) {
					clearInterval(heart_beat_inteval)
				}
				if (this.currentVideoId) {
					this.$u.api.stopVideo({
						videoId: this.currentVideoId
					})
					this.currentVideoId = null
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.wrap {
		background-color: #000;
		height: 100vh;

		.category-items {
			display: flex;
			flex-wrap: wrap;
			margin-bottom: 100upx;

			.category-item {
				background-color: #ebebeb;
				margin: 6px 10upx 0 10upx;
				padding: 4upx 8upx;
				border-radius: 10upx;
			}

			.category-item-active {
				background-color: #EE6666;
				color: #fff;
			}
		}
	}
</style>
